import React, { useState, useEffect } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

const ConfigPage = () => {
    const location = useLocation();
    const navigate = useNavigate();
    const [data, setData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);
    const { selectedTableName } = location.state || {};

    // 调用后端接口获取全部数据
    const fetchData = async () => {
        setIsLoading(true);
        try {
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/selectConfList`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            console.log(result);
            if (result.code === 200 && result.data !== '') {
                console.log("result输出：", result.data);
                setData(result.data); // 假设返回的数据格式为 { data: [...] }
            }
        } catch (error) {
            console.error('Error fetching data:', error);
        } finally {
            setIsLoading(false);
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

    // 处理详情按钮点击
    const handleDetailClick =async (url) => {
        console.log(`详情按钮点击，ID: ${url}`);
        // 这里可以跳转到详情页面或显示详情模态框
        try {
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/selectConfig?url=${url}`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            console.log("result:",result);
            const jsonObject = JSON.parse(result.data.content);
            console.log("jsonObject:",jsonObject);
            if (result.code === 200) {
                // const options = result.data.map((type) => ({ value: type, label: type }));
                console.log(result.data);
                navigate('/ConfigDetailPage', {
                    state: {
                        detailData: result.data
                    }})
            }
        } catch (error) {
            console.error('Error fetching column type options:', error);
        }

    };

    // 处理删除按钮点击
    const handleDeleteClick =async (id) => {
        try {
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/delConfig?id=${id}`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result = await response.json();
            if (result.code === 200 && Array.isArray(result.data)) {
                const options = result.data.map((type) => ({ value: type, label: type }));
                console.log(options);
                // setColumnTypeOptions(options);
            }
        } catch (error) {
            console.error('Error fetching column type options:', error);
        }
    };

    // 处理新增按钮点击
    const handleAddClick = () => {
        navigate('/add-config'); // 跳转到新增配置页面
    };

    return (
        <div>
            <h1>配置页面 - {selectedTableName}</h1>
            <button onClick={handleAddClick} style={{ marginBottom: '20px' }}>
                新增
            </button>
            {isLoading ? (
                <p>加载中...</p>
            ) : (
                <table border="1" cellPadding="10" cellSpacing="0">
                    <thead>
                        <tr>
                            {/* <th>ID</th> */}
                            <th>路径</th>
                            <th>表名</th>
                            <th>配置</th>
                        </tr>
                    </thead>
                    <tbody>
                        {data.map((item) => (
                            <tr key={item.id}>
                                {/* <td>{item.id}</td> */}
                                <td>{item.url}</td>
                                <td>{item.tableName}</td>
                                <td>
                                    <button onClick={() => handleDetailClick(item.url)}>详情</button>
                                    <button onClick={() => handleDeleteClick(item.id)}>删除</button>
                                </td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            )}
        </div>
    );
};

export default ConfigPage;